"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Send, MessageSquare, Bot, User, ChevronDown, ChevronUp, Sparkles } from "lucide-react";

interface ChatMessage {
  id: string;
  content: string;
  sender: "user" | "assistant";
  nickname?: string;
  timestamp: Date;
}

interface TerminalChatProps {
  onSendMessage: (message: string) => void;
  messages?: ChatMessage[];
  disabled?: boolean;
  placeholder?: string;
  minHeight?: string;
  maxHeight?: string;
}

export default function TerminalChat({
  onSendMessage,
  messages = [],
  disabled = false,
  placeholder = "Type your message...",
  minHeight = "200px",
  maxHeight = "400px"
}: TerminalChatProps) {
  const [inputValue, setInputValue] = useState("");
  const [isExpanded, setIsExpanded] = useState(true);
  const [isComposing, setIsComposing] = useState(false);
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Scroll to bottom when messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // Focus input when expanded
  useEffect(() => {
    if (isExpanded && !disabled) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }
  }, [isExpanded, disabled]);

  const toggleExpand = useCallback(() => {
    setIsExpanded(!isExpanded);
  }, [isExpanded]);


  // Handle keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+/ or Cmd+/ to toggle chat
      if ((e.ctrlKey || e.metaKey) && e.key === '/') {
        e.preventDefault();
        toggleExpand();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [toggleExpand]);

  const handleSendMessage = useCallback(() => {
    if (inputValue.trim() && !disabled && !isComposing) {
      setIsTyping(true);
      onSendMessage(inputValue.trim());
      setInputValue("");
      // Simulate typing indicator for a short time
      setTimeout(() => setIsTyping(false), 1000);
    }
  }, [inputValue, onSendMessage, disabled, isComposing]);

  const handleKeyPress = useCallback((e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  }, [handleSendMessage]);

  const handleCompositionStart = useCallback(() => {
    setIsComposing(true);
  }, []);

  const handleCompositionEnd = useCallback(() => {
    setIsComposing(false);
  }, []);

  const formatTime = useCallback((date: Date) => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }, []);

  return (
    <div className="bg-gray-900 border-t border-gray-700">
      {/* Chat Header */}
      <div className="flex items-center justify-between px-4 py-3 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
            <Bot className="h-4 w-4 text-white" />
          </div>
          <div>
            <span className="text-sm font-semibold text-gray-100">AI Assistant</span>
            {messages.length > 0 && (
              <div className="text-xs text-gray-400">
                {messages.length} message{messages.length !== 1 ? 's' : ''}
              </div>
            )}
          </div>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={toggleExpand}
          className="h-8 w-8 p-0 hover:bg-gray-700 rounded-full transition-colors"
        >
          {isExpanded ? (
            <ChevronDown className="h-4 w-4 text-gray-400" />
          ) : (
            <ChevronUp className="h-4 w-4 text-gray-400" />
          )}
        </Button>
      </div>

      {/* Chat Content */}
      {isExpanded && (
        <div className="flex flex-col" style={{ minHeight, maxHeight }}>
          {/* Messages Area */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-900">
            {messages.length === 0 ? (
              <div className="text-center py-12">
                <div className="relative w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
                  <Bot className="h-8 w-8 text-white" />
                  <div className="absolute -top-1 -right-1 w-4 h-4 bg-gradient-to-r from-yellow-400 to-orange-500 rounded-full flex items-center justify-center animate-pulse">
                    <Sparkles className="h-2 w-2 text-white" />
                  </div>
                </div>
                <h3 className="text-lg font-medium text-gray-200 mb-2">Welcome to AI Chat</h3>
                <p className="text-sm text-gray-500 max-w-sm mx-auto leading-relaxed">
                  Ask me anything about your terminal session, code, or get help with commands. I'm here to assist you!
                </p>
              </div>
            ) : (
              messages.map((message, index) => (
                <div
                  key={message.id}
                  className={`flex items-start space-x-3 animate-in slide-in-from-bottom-2 duration-300 ${
                    message.sender === "user" ? "justify-end" : "justify-start"
                  }`}
                  style={{ animationDelay: `${index * 50}ms` }}
                >
                  {message.sender === "assistant" && (
                    <div className="flex-shrink-0 mt-1">
                      <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                        <Bot className="h-4 w-4 text-white" />
                      </div>
                    </div>
                  )}

                  <div
                    className={`max-w-[75%] rounded-2xl px-4 py-3 shadow-sm ${
                      message.sender === "user"
                        ? "bg-blue-600 text-white rounded-br-md"
                        : "bg-gray-800 text-gray-100 rounded-bl-md border border-gray-700"
                    }`}
                  >
                    {message.sender === "assistant" && message.nickname && (
                      <div className="text-xs text-blue-400 mb-1 font-medium">
                        {message.nickname}
                      </div>
                    )}
                    <div className="text-sm leading-relaxed break-words whitespace-pre-wrap">
                      {message.content}
                    </div>
                    <div
                      className={`text-xs mt-2 ${
                        message.sender === "user"
                          ? "text-blue-100"
                          : "text-gray-400"
                      }`}
                    >
                      {formatTime(message.timestamp)}
                    </div>
                  </div>

                  {message.sender === "user" && (
                    <div className="flex-shrink-0 mt-1">
                      <div className="w-8 h-8 bg-gray-600 rounded-full flex items-center justify-center">
                        <User className="h-4 w-4 text-white" />
                      </div>
                    </div>
                  )}
                </div>
              ))
            )}
            
            {/* Typing Indicator */}
            {isTyping && (
              <div className="flex items-start space-x-3 justify-start animate-in slide-in-from-bottom-2 duration-300">
                <div className="flex-shrink-0 mt-1">
                  <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                    <Bot className="h-4 w-4 text-white" />
                  </div>
                </div>
                <div className="max-w-[75%] rounded-2xl px-4 py-3 shadow-sm bg-gray-800 text-gray-100 rounded-bl-md border border-gray-700">
                  <div className="flex items-center space-x-1">
                    <div className="flex space-x-1">
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                    </div>
                    <span className="text-xs text-gray-400 ml-2">AI is typing...</span>
                  </div>
                </div>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </div>

          {/* Input Area */}
          <div className="p-4 bg-gray-800 border-t border-gray-700">
            <div className="flex items-end space-x-3">
              <div className="flex-1 relative">
                <Input
                  ref={inputRef}
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  onCompositionStart={handleCompositionStart}
                  onCompositionEnd={handleCompositionEnd}
                  placeholder={disabled ? "Chat is disabled..." : "Type your message..."}
                  disabled={disabled}
                  className="w-full bg-gray-700 border-gray-600 text-white placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-xl px-4 py-3 pr-12 resize-none transition-colors"
                />
                <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                  <Button
                    onClick={handleSendMessage}
                    disabled={!inputValue.trim() || disabled || isComposing}
                    size="sm"
                    className={`h-8 w-8 p-0 rounded-lg transition-all duration-200 ${
                      inputValue.trim() && !disabled && !isComposing
                        ? 'bg-blue-600 hover:bg-blue-700 hover:scale-105 shadow-lg'
                        : 'bg-gray-600 cursor-not-allowed'
                    }`}
                  >
                    <Send className={`h-4 w-4 transition-transform duration-200 ${
                      inputValue.trim() && !disabled && !isComposing ? 'scale-100' : 'scale-90'
                    }`} />
                  </Button>
                </div>
              </div>
            </div>

            {/* Input Hints */}
            {!disabled && (
              <div className="flex items-center justify-between mt-3 text-xs text-gray-500">
                <div className="flex items-center space-x-4">
                  <span className="flex items-center space-x-1">
                    <kbd className="px-2 py-1 bg-gray-700 rounded text-xs font-mono">Enter</kbd>
                    <span>to send</span>
                  </span>
                  <span className="flex items-center space-x-1">
                    <kbd className="px-2 py-1 bg-gray-700 rounded text-xs font-mono">Shift+Enter</kbd>
                    <span>new line</span>
                  </span>
                </div>
                <div className="flex items-center space-x-1">
                  <kbd className="px-2 py-1 bg-gray-700 rounded text-xs font-mono">Ctrl+/</kbd>
                  <span>toggle</span>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
